package br.com.fatec.cqr.view;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.metal.MetalFileChooserUI;

import br.com.fatec.cqr.control.model.Comando;
import br.com.fatec.cqr.control.mongo.ListaDeComandosMongo;
import br.com.fatec.cqr.control.sql.ListaDeComandos;
import br.com.fatec.cqr.main.Principal;

public class Action implements ActionListener {

	/*
	 * A��es dos primeiros bot�es do Primeiro JToolBar
	 */

	/*
	 * Implementado a acao de salvar arquivo em .txt
	 */
	public void saveAction(JEditorPane displaySql, JTabbedPane query) {
		String texto = new String();

		UIManager.put("FileChooser.openButtonToolTipText", "Save");
		UIManager.put("FileChooser.openButtonAccessibleName", "Save");
		UIManager.put("FileChooser.openButtonText", "Save");
		UIManager.put("FileChooser.cancelButtonText", "Cancel");

		JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setDialogTitle("Save");

		int i = query.getSelectedIndex();

		MetalFileChooserUI ui = (MetalFileChooserUI) fileChooser.getUI();
		Field field;
		try {
			field = MetalFileChooserUI.class
					.getDeclaredField("fileNameTextField");
			field.setAccessible(true);
			JTextField tf;
			try {
				tf = (JTextField) field.get(ui);
				if (i != -1) {
					tf.setText(query.getTitleAt(i));
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}

		if (i != -1) {
			JScrollPane scroll = (JScrollPane) query.getComponentAt(i);

			JViewport vp = scroll.getViewport();
			for (Component comp : vp.getComponents()) {
				if (comp instanceof JEditorPane) {
					JEditorPane jta = (JEditorPane) comp;
					texto = jta.getText();
				}
			}

			int status = fileChooser.showOpenDialog(null);
			if (status == JFileChooser.APPROVE_OPTION) {
				File file = fileChooser.getSelectedFile();

				PrintWriter pw = null;
				String[] nomeArquivo = file.getAbsolutePath().split("\\.");
				String title = nomeArquivo[0];
				if (nomeArquivo.length > 1) {
					try {

						if (file.exists()
								&& JOptionPane
										.showConfirmDialog(
												null,
												"The file already exists, would you like to overwrite it?",
												"File already exists", 0) != JOptionPane.OK_OPTION) {
							return;
						}
						pw = new PrintWriter(new FileWriter(file));
						pw.println(texto);
						pw.close();
						query.setTitleAt(i, file.getName());
					} catch (IOException e) {
						e.printStackTrace();

					}
				} else {
					try {
						if (file.exists()
								&& JOptionPane
										.showConfirmDialog(
												null,
												"The file already exists, would you like to overwrite it?",
												"File already exists", 0) != JOptionPane.OK_OPTION) {
							return;

						}
						pw = new PrintWriter(new FileWriter(file + ".sql"));
						pw.println(texto);
						pw.close();
						query.setTitleAt(i, file.getName() + ".sql");
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			}

		}
	}

	public void export(JEditorPane pane) {

		UIManager.put("FileChooser.openButtonToolTipText", "Export");
		UIManager.put("FileChooser.openButtonAccessibleName", "Export");
		UIManager.put("FileChooser.openButtonText", "Export");
		UIManager.put("FileChooser.cancelButtonText", "Cancel");

		JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setDialogTitle("Export");

		int status = fileChooser.showOpenDialog(null);
		if (status == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();

			PrintWriter pw = null;
			String[] nomeArquivo = file.getAbsolutePath().split("\\.");
			String title = nomeArquivo[0];
			if (nomeArquivo.length > 1) {
				try {

					if (file.exists()
							&& JOptionPane
									.showConfirmDialog(
											null,
											"The file already exists, would you like to overwrite it?",
											"File already exists", 0) != JOptionPane.OK_OPTION) {
						return;
					}
					pw = new PrintWriter(new FileWriter(file));
					pw.println(pane.getText());
					pw.close();
				} catch (IOException e) {
					e.printStackTrace();

				}
			} else {
				try {
					if (file.exists()
							&& JOptionPane
									.showConfirmDialog(
											null,
											"The file already exists, would you like to overwrite it?",
											"File already exists", 0) != JOptionPane.OK_OPTION) {
						return;
					}
					pw = new PrintWriter(new FileWriter(file + ".sql"));
					pw.println(pane.getText());
					pw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		}
	}

	public void newQuery(JTabbedPane query, JPanel textPanel) {
		UIManager.put("OptionPane.cancelButtonText", "Cancel");
		String title = "";
		Icon imageIcon = new ImageIcon(
				"/br/com/fatec/cqr/view/resources/logo_aplicacao.png");

		title = JOptionPane.showInputDialog(null, "Enter the Name:",
				"New Query", JOptionPane.PLAIN_MESSAGE);
		if (title != null) {
			query.setFont(new Font("Arial", Font.PLAIN, 12));

			EditorPane display = new EditorPane();
			display.setFont(new Font("Arial", Font.BOLD, 14));
			display.setForeground(new Color(0, 0, 205));

			JScrollPane scroll = new JScrollPane(display);
			scroll.setVerticalScrollBarPolicy(scroll.VERTICAL_SCROLLBAR_ALWAYS);

			query.add(title, scroll);
			textPanel.add(query);
			int i = query.getComponentCount();
			i -= 1;
			query.setSelectedIndex(i);
		}
	}

	public void close(JTabbedPane query) {
		int i = query.getSelectedIndex();
		if (i != -1) {
			query.removeTabAt(i);
		}
	}

	public void openFile(JTabbedPane query, JPanel textPanel) {
		UIManager.put("FileChooser.openButtonToolTipText", "Open");
		UIManager.put("FileChooser.openButtonAccessibleName", "Open");
		UIManager.put("FileChooser.openButtonText", "Open");
		UIManager.put("FileChooser.cancelButtonText", "Cancel");
		try {
			JFileChooser fc = new JFileChooser();
			fc.setDialogTitle("Open");
			fc.setFileFilter(new FileNameExtensionFilter("Arquivo SQL", "sql",
					"txt"));
			fc.setAcceptAllFileFilterUsed(false);
			fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

			int resultado = fc.showOpenDialog(null);

			File fileName = fc.getSelectedFile();
			FileReader input = new FileReader(fileName);

			BufferedReader bufRead = new BufferedReader(input);
			// Criando a aba
			String title = fileName.getName();

			query.setFont(new Font("Arial", Font.PLAIN, 12));
			EditorPane display = new EditorPane();
			display.setFont(new Font("Arial", Font.BOLD, 14));
			display.setForeground(new Color(0, 0, 205));

			JScrollPane scroll = new JScrollPane(display);
			scroll.setVerticalScrollBarPolicy(scroll.VERTICAL_SCROLLBAR_ALWAYS);

			query.add(title, scroll);
			textPanel.add(query);

			String linha = null;
			while ((linha = bufRead.readLine()) != null) {
				String res = display.getText();
				linha += "\n" + res;
				display.setText(linha);

				int i = query.getComponentCount();
				i -= 1;
				query.setSelectedIndex(i);
			}

			bufRead.close();

		} catch (ArrayIndexOutOfBoundsException e1) {
			System.out.println("Erro");
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (NullPointerException e3) {

		}

	}

	/*
	 * Por enquanto s� esta pegando o conteudo do display e colocando no
	 * displayNoSql
	 */
	public void runAction(JTabbedPane query, EditorPane display,
			JEditorPane displayNoSql) {
		String syntax = "";
		syntax = display.getText();
		int i = 0;
		i = query.getSelectedIndex();
		if (i != -1) {
			JScrollPane scroll = (JScrollPane) query.getComponentAt(i);

			JViewport vp = scroll.getViewport();
			for (Component comp : vp.getComponents()) {
				if (comp instanceof JEditorPane) {
					JEditorPane jta = (JEditorPane) comp;
					String textoSql = jta.getText();
					textoSql = textoSql.replace("\n", "");
					String[] textosSql = textoSql.split(";");
					displayNoSql.setText("");
					String retorno = "";
					for (int j = 0; j < textosSql.length; j++) {

						textoSql = textosSql[j].replace(" ", "")
								.replace("\n", "").toLowerCase();
						ListaDeComandos listaDeComandos = new ListaDeComandos();
						ListaDeComandosMongo listaDeComandosMongo = new ListaDeComandosMongo();
						if (Principal.mongoConvertido) {
							for (Comando c : listaDeComandos) {
								if (textoSql.matches(c.expressao())) {
									retorno += c.conversao(textoSql) + "\n";
								}

							}

						} else {
							for (Comando c : listaDeComandosMongo) {
								if (textoSql.matches(c.expressao())) {
									retorno += c.conversao(textoSql) + "\n";
								}
							}
						}

						displayNoSql.setText(retorno);
						jta.setText("");

					}

				}
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		// MENU FILE
		// SUBMENU DE NEW E PROJECT
		if (cmd.equalsIgnoreCase("Exit                                                  Alt+F4")) {
			System.exit(0);

			// MENU TOOLS
		} else if (cmd.equalsIgnoreCase("  View Help")) {
			JOptionPane
					.showMessageDialog(
							null,
							"A respeito do simple-db\n\nO simple-db � um sistema criado para "
									+ "auxiliar DBA`s que estao trabalhando pela primeira vez com um banco de dados n�o \nrelacional. "
									+ "Ele oferece a possibilidade do administrador de banco de dados criar suas consultas atrav�s"
									+ " da linguagem estruturada \nSQL e converte-las para a linguagem MongoDB. Para ver informacoes "
									+ "completas sobre cada funcionalidade fornecida pelo \nsistema v� para a guia *Funcionalidades."
									+ "\n\n\n\n"
									+ "O uso do simple-db\n\n1*  Insira a sua consulta, dentro da area de digitacao, na aba query "
									+ "prestando atencao nas palavras reservadas do SQL.\n2*  Clique em Translate na parte superior da tela, "
									+ "representada por uma seta verde, para iniciar a conversao para o NoSQL.\n3*  Selecione o resultado na area "
									+ "NoSQL em seguida pressione Ctrl+C para copiar"
									+ " o resultado.");

		} else if (cmd.equalsIgnoreCase("About...")) {
			JOptionPane
					.showMessageDialog(
							null,
							"Developed by: \nAkau� Silva - akaua.silva@gmail.com\nFelipe Barbosa - fbarbosa.1993@gmail.com\nThiago Greccofi - thiago.greccofi@gmail.com\n",
							"About", JOptionPane.PLAIN_MESSAGE);
		} else if (cmd.equalsIgnoreCase(" Open File")
				|| (cmd.equalsIgnoreCase("  Open"))) {
			JTabbedPane query = PainelSql.query;
			JPanel textPanel = PainelSql.textPanel;
			this.openFile(query, textPanel);
		} else if (cmd.equalsIgnoreCase("Save")
				|| (cmd.equalsIgnoreCase("  Save"))) {
			EditorPane display = PainelSql.display;
			JTabbedPane query = PainelSql.query;
			this.saveAction(display, query);
		} else if (cmd.equalsIgnoreCase(" New Query")
				|| (cmd.equalsIgnoreCase("New"))) {
			JTabbedPane query = PainelSql.query;
			JPanel textPanel = PainelSql.textPanel;
			this.newQuery(query, textPanel);
		} else if (cmd.equalsIgnoreCase(" Translate")) {
			JTabbedPane query = PainelSql.query;
			EditorPane display = PainelSql.display;
			JEditorPane displayNoSql = PainelNoSql.displayNoSql;
			this.runAction(query, display, displayNoSql);
		} else if (cmd.equalsIgnoreCase(" Export")) {
			JEditorPane displayNoSql = PainelNoSql.displayNoSql;
			this.export(displayNoSql);
		} else if (cmd.equalsIgnoreCase(" Close")) {
			JTabbedPane query = PainelSql.query;
			this.close(query);

		} else if (cmd.equalsIgnoreCase("MongoDB Nativo")) {
			Principal.mongoNativo = true;
			Principal.mongoConvertido = false;
		} else if (cmd.equalsIgnoreCase("MongoDB Convertido")) {
			Principal.mongoConvertido = true;
			Principal.mongoNativo = false;
		} else if (cmd.equalsIgnoreCase("comboBoxChanged")) {

			JComboBox cb = (JComboBox) e.getSource();
			String selectedOption = cb.getSelectedItem().toString();
			Principal.selectedOption = selectedOption;

			if ("comboBoxChanged".equals(e.getActionCommand())) {
				Principal.db = Principal.mongoClient.getDB(selectedOption);
			}

		}

	}

	public void undo() {
		Robot robot;
		try {

			int i = new Action().retornaAbaAtiva();
			if (i != -1) {
				JScrollPane scroll = (JScrollPane) PainelSql.query
						.getComponentAt(i);

				JViewport vp = scroll.getViewport();
				for (Component comp : vp.getComponents()) {
					if (comp instanceof JEditorPane) {
						JEditorPane jta = (JEditorPane) comp;
						robot = new Robot();
						robot.keyPress(KeyEvent.VK_CONTROL);
						robot.keyPress(KeyEvent.VK_Z);
						jta.requestFocus();
						robot.keyRelease(KeyEvent.VK_CONTROL);
						robot.keyRelease(KeyEvent.VK_Z);
					}
				}

			}
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void redo() {
		Robot robot;
		try {

			int i = new Action().retornaAbaAtiva();
			if (i != -1) {
				JScrollPane scroll = (JScrollPane) PainelSql.query
						.getComponentAt(i);

				JViewport vp = scroll.getViewport();
				for (Component comp : vp.getComponents()) {
					if (comp instanceof JEditorPane) {
						JEditorPane jta = (JEditorPane) comp;
						robot = new Robot();
						robot.keyPress(KeyEvent.VK_CONTROL);
						robot.keyPress(KeyEvent.VK_Y);
						jta.requestFocus();
						robot.keyRelease(KeyEvent.VK_CONTROL);
						robot.keyRelease(KeyEvent.VK_Y);
					}
				}
			}
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	public int retornaAbaAtiva() {
		JTabbedPane query = PainelSql.query;
		int i = query.getSelectedIndex();
		return i;
	}

}
